#include "stdafx.h"
#include "FixFileProcessor.h"
#include "DateTime.h"

FixFileProcessor::FixFileProcessor(CircleDequeueBase* p_pcCircleQueue,
	const unsigned int p_uiInterval, 
	string p_strFilePath, 
	const unsigned int p_uiBufferSize,
	bool p_bVerifyLocalTime,
	unsigned int p_uiFileType)
	:FileBase(p_strFilePath,p_uiBufferSize)
	,m_pcCircleQueue(p_pcCircleQueue)
	,m_uiInterval(p_uiInterval)
	,m_bVerifyLocalTime(p_bVerifyLocalTime)
	,m_uiFileType(p_uiFileType)
{
	memset(m_szLastDBFDate,0,8);
}

bool FixFileProcessor::Process()
{
	cout << "Start to process file " << m_uiFileType; // for test

	// Read from file
	if(false == FileBase::OpenFile())
	{
		LOG(ERROR) << "Open file error";
		return false;
	}

	// Process data
	if (m_uiFileLength > 0 && (NULL != m_pszBuffer))
	{
		// Get DBF time and local time
		DbfHeadNew* pstDBFHead = (DbfHeadNew*)m_pszBuffer;
		FieldElement* pstField = (FieldElement*)(m_pszBuffer + sizeof(DbfHeadNew));
		//Time stDBFTime;
		//FileBase::GetDBFTime(stDBFTime,m_uiFileType);
		//Time stDBFDate;
		//FileBase::GetDBFDate(stDBFDate,m_uiFileType);
		string strLocalDate = DateTime::GetLocalDate();

		// Compare DBF time with local time
		//if (memcmp(m_szLastDBFDate,stLocalDate.szTime,8) != 0)
		//{
		//	LOG(ERROR) << "DBF time is dismatch with local time";
		//	return false;
		//}

		// Get last DBF buffer
		char* szLastDBFBuffer = NULL;
		unsigned int uiLastBufferLength = m_pcCircleQueue->GetEntireBuffer(&szLastDBFBuffer);

		//DbfHeadNew* pstLastDBFHead = (DbfHeadNew*)szLastDBFBuffer;
		//if (memcmp(m_szLastDBFDate,strLocalDate.data(),8) != 0) // Last DBF and new DBF file date is dismatch
		//{
		//	// Write to circle queue
		//	//LOG(INFO) << "Last dbf date is not same with current dbf date. File type : " << m_uiFileType;
		//	m_pcCircleQueue->SetEntireFlag();
		//	m_pcCircleQueue->WriteData(m_pszBuffer, m_uiFileLength);
		//}
		//else 
		if ((uiLastBufferLength != m_uiFileLength) || memcmp(szLastDBFBuffer,m_pszBuffer,m_uiFileLength) != 0) // Last DBF and new DBF data buffer are same
		{
			// Write to circle queue
			m_pcCircleQueue->SetEntireFlag();
			m_pcCircleQueue->WriteData(m_pszBuffer, m_uiFileLength);
		}
	}

	FileBase::CloseFile();

	return true;
}